package com.hnair.grpc.example.interceptor;

import io.grpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class TokenInterceptor extends BaseServerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    public String getHeader(Metadata headers, String key) {
        return headers.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER));
    }


    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        logger.debug("Token Interceptor");
        ServerCall.Listener<ReqT> listener;
        String client_id = getHeader(headers, "client_id");
        if (StringUtils.isEmpty(client_id)) {
            listener = close(call, headers, Status.PERMISSION_DENIED, "11");
        } else {
            Context context = Context.current().withValue(Context.key("session_id"), "111");
            listener = Contexts.interceptCall(context, call, headers, next);
        }

        return listener;

    }
}
